package com.smart.ioc.resource;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.support.ServletContextResource;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 测试读取文件
 *
 * @author junrui.wang
 * @create 2018/4/18
 */
public class ResourceTest {
    public static void main(String[] args) throws IOException {
        String filePath = "D:\\Git\\chapter1\\src\\main\\webapp\\WEB-INF\\conf\\file.txt";
        //如果位于WEB应用的类路径下，可以通过三种方式访问
        //通过FileSystemResource以文件绝对路径进行访问
        Resource res1 = new FileSystemResource(filePath);
        InputStream in1 = res1.getInputStream();
        ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
        int i = 0;
        while((i=in1.read()) != -1){
            baos1.write(i);
        }
        System.out.println(baos1.toString());

        //通过ClassPathResource以类路径的方式进行访问
        Resource res2 = new ClassPathResource("conf/file.txt");
        InputStream in2 = res2.getInputStream();
        ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
        i = 0;
        while((i=in2.read()) != -1){
            baos2.write(i);
        }
        System.out.println(baos2.toString());

        //通过ServletContextResource以相对于Web应用根目录的方式进行访问
        /*
            1.在javax.servlet.Filter中直接获取

            ServletContext context = config.getServletContext();

            2.在HttpServlet中直接获取

            this.getServletContext()

            3.在其他方法中，通过HttpRequest获得

            request.getSession().getServletContext();
         */
        /*Resource res3 = new ServletContextResource(ServletContext context, "WEB-INF/conf/file.txt");
        InputStream in3 = res3.getInputStream();
        ByteArrayOutputStream baos3 = new ByteArrayOutputStream();
        i = 0;
        while((i=in3.read()) != -1){
            baos3.write(i);
        }
        System.out.println(baos3.toString());*/

        //UrlResource可以读取远程服务器（WEB服务器或者FTP服务器）的文件资源
        UrlResource res4 = new UrlResource("http://12.12.12.12/adaf.jpg");

        //指定特殊的编码格式读取资源，用EncodedResource
        Resource res5 = new ClassPathResource("conf/file.txt");
        EncodedResource er = new EncodedResource(res5, "UTF-8");
        String content = FileCopyUtils.copyToString(er.getReader());
        System.out.println(content);
    }

}
